import { useState, useEffect } from 'react';
import { withRouter } from 'next/router';
import { queryCheckEmpty } from '@/utils';
import Head from '@/components/Head';
import Tkd from '@/ssr/tkd';
// css
import styles from '@/styles/CommonList.module.scss';
// 组件
import Breadcrumb from '@/components/Breadcrumb';
import Pagination from '@/components/Pagination';
import ListItem from '@/pages_components/list/ListItem';
import HotProductPart from '@/pages_components/components/HotProductPart';
import Empty from '@/pages_components/list/Empty';
// ssr api
import { productList_SSR } from '@/ssr';
import { routeFilters } from '@/api/line';

const pageType = '/line';
const Route = ({ router, list, total }) => {

    // 筛选条件，初始化
    const _filters = {
        cities: [
            { label: '全部', value: '', chosen: true },
            { label: '林芝', value: '林芝' },
            { label: '拉萨', value: '拉萨' },
            { label: '阿里', value: '阿里' }
        ],
        recomends: [{ label: '全部', value: '', chosen: true }],
        services: [{ label: '全部', value: '', chosen: true }],
        gathers: [{ label: '全部', value: '', chosen: true }],
    };

    // 筛选
    const [filters, setFilters] = useState(_filters);
    const { query } = router;

    // api获取筛选条件
    useEffect(() => {
        queryHandler('city', query['city']);
        // “精选推荐”、“服务亮点”、“集合方式”
        routeFilters('PD-LINE-03').then(res => {
            const r = (res.data && res.data || []).map(item => {
                return { label: item.name, value: item.id }
            })
            _filters['recomends'] = _filters['recomends'].concat(r);
            queryHandler('r', query['r']);
        })
        routeFilters('PD-LINE-04').then(res => {
            const r = (res.data && res.data || []).map(item => {
                return { label: item.name, value: item.id }
            })
            _filters['services'] = _filters['services'].concat(r);
            queryHandler('s', query['s']);
        })
        routeFilters('PD-LINE-05').then(res => {
            const r = (res.data && res.data || []).map(item => {
                return { label: item.name, value: item.id }
            })
            _filters['gathers'] = _filters['gathers'].concat(r);
            queryHandler('g', query['g']);
        })
    }, []);

    // 通过nav切换回本页面第一页，去掉选中筛选
    useEffect(() => {
        if(router.asPath === router.pathname){
            queryHandler('city', '', true);
            queryHandler('r', '', true);
            queryHandler('s', '', true);
            queryHandler('g', '', true);
        }
    }, [router.asPath]);

    // 已筛选条件
    function queryHandler(key, val) {
        switch(key){
            case 'city': {
                choseFilter('cities', val, true)
                break
            }
            case 'r': {
                choseFilter('recomends', val, true)
                break
            }
            case 's': {
                choseFilter('services', val, true)
                break
            }
            case 'g': {
                choseFilter('gathers', val, true)
                break
            }
        }
    }
    // 统一路由处理
    function routeHandler() {
        let _query = { ...query };
        let city = filters['cities'].filter(item => item.chosen).map(item => item.value).toString(),
            recomend = filters['recomends'].filter(item => item.chosen).map(item => item.value).toString(),
            service = filters['services'].filter(item => item.chosen).map(item => item.value).toString(),
            gather = filters['gathers'].filter(item => item.chosen).map(item => item.value).toString();
        _query['city'] = city;
        _query['r'] = recomend;
        _query['s'] = service;
        _query['g'] = gather;
        
        let newQuery = queryCheckEmpty(_query);
        router.push({
            pathname: pageType,
            query: newQuery
        })
    }
    // 筛选条件，选中
    function choseFilter(key, value, init) {
        filters[key].forEach(f => {
            f.chosen = false
            if ((!f.value && !value) || f.value == value) {
                f.chosen = true;
            }
        });
        setFilters({ ...filters });
        !init && routeHandler();
    }

    // 筛选条件 Component
    const Filters = (
        <>
            <dl>
                <dt>出发城市</dt>
                <dd>
                    {
                        filters.cities.map(item => {
                            return <span onClick={() => { choseFilter('cities', item.value) }} className={item.chosen ? styles['selected'] : ''} key={item.value}>{item.label}</span>
                        })
                    }
                </dd>
            </dl>
            <dl>
                <dt>精选推荐</dt>
                <dd>
                    {
                        filters.recomends.map(item => {
                            return <span onClick={() => { choseFilter('recomends', item.value) }} className={item.chosen ? styles['selected'] : ''} key={item.value}>{item.label}</span>
                        })
                    }
                </dd>
            </dl>
            <dl>
                <dt>服务亮点</dt>
                <dd>
                    {
                        filters.services.map(item => {
                            return <span onClick={() => { choseFilter('services', item.value) }} className={item.chosen ? styles['selected'] : ''} key={item.value}>{item.label}</span>
                        })
                    }
                </dd>
            </dl>
            <dl>
                <dt>集合方式</dt>
                <dd>
                    {
                        filters.gathers.map(item => {
                            return <span onClick={() => { choseFilter('gathers', item.value) }} className={item.chosen ? styles['selected'] : ''} key={item.value}>{item.label}</span>
                        })
                    }
                </dd>
            </dl>
        </>
    )

    return (
        <div className={styles['common-list-page']}>
            {/* 标题/关键字/网页描述 */}
            <Head meta={Tkd[pageType]} />
            {/* 网页内容 */}
            <div className="max-content">
                {/* 面包屑 */}
                <Breadcrumb params={[{ name: '线路预订', url: pageType }]} />
                <div className={styles.cnt}>
                    {/* 左侧 */}
                    <div className={styles['cnt-left']}>
                        {/* 筛选 */}
                        <div className={styles['filter']}>
                            {Filters}
                        </div>
                        {/* 列表 */}
                        <div className={styles['pro-list']}>
                            {
                                !list.length
                                ? <Empty />
                                : list.map(item => {
                                    return <ListItem target={pageType} targetUrl={`${pageType}/${item.id}.html`} data={item} key={item.id} />
                                })
                            }
                        </div>
                        {/* 分页 */}
                        <Pagination root={pageType} total={total} />
                    </div>
                    {/* 右侧，热门列表 */}
                    <div className={styles['cnt-right']}>
                        <HotProductPart product="热门线路" target="/line" />
                    </div>
                </div>
            </div>
        </div>
    )
}

// ssr 请求
Route.getInitialProps = async (ctx) => {
    const { pathname, query } = ctx;
    const { 
        ssr: list, 
        total
    } = await productList_SSR(pageType, { pathname, query });
    return { list, total }
}

export default withRouter(Route)